<template>
	<view :class="{ yejian: if_theme_dark }">
		<!--#ifdef APP-PLUS-->
		<view class="lz-status_bar">
			<view class="lz-top_view"></view>
		</view>
		<!--#endif-->
		<view class="kaoshi-head">
			<view class="kaoshi-head-top">
				<view class="kaoshi-head-left" @tap="$navigateBack">
					<view class="iconfont icon-zuojiantou"></view>
				</view>
				<view class="kaoshi-head-m">
					{{ pages_params.title }}
				</view>
				<view class="kaoshi-head-right"></view>
			</view>
		</view>
		<view scroll-y style="height: 100%;">
			<view style="height: 10px;"></view>
			<view class="questionBankAnswer" v-if="current_timu && current_timu.id">

				<question-type :current_timu="current_timu" :timu_order="timu_order" :total_num="total_num" :over_time="over_time"
					@timeup="timeup"></question-type>
			</view>
			<view class="questionBankAnswer-content" v-if="current_timu && current_timu.answers">
				<question-title :node="current_timu.question_name"></question-title>
				<block v-for="(item, index) in current_timu.answers" :key="index">
					<question-option :show_beiti="false" :ref="'questionOption_' + index" :item="item" :index="index"
						:current_timu="current_timu" :copy_user_answer="copy_user_answer" :timu_index="timu_order - 1"
						:copy_post_status="copy_post_status" @post_answer_req="post_answer_req"
						@set_copy_user_answer="set_copy_user_answer" @set_sub_button_style="set_sub_button_style"
						question_type="exam"></question-option>
				</block>
				<template v-if="current_timu.type == 4">
					<question-tiankong :show_beiti="false" :current_timu="current_timu" :is_tiankong_sub="is_tiankong_sub"
						@set_current_timu="set_current_timu" @post_answer_req="post_answer_req"
						@set_sub_button_style="set_sub_button_style">
					</question-tiankong>
				</template>
				<template v-else-if="current_timu.type == 5">
					<question-jianda :show_beiti="false" :current_timu="current_timu" :is_jianda_sub="is_jianda_sub"
						@set_current_timu="set_current_timu" @post_answer_req="post_answer_req"
						@set_sub_button_style="set_sub_button_style"></question-jianda>
				</template>
				<view v-if="current_timu.answers && current_timu.type == 2">
					<button :class="is_duoxuan_sub ? 'duoxuan_checked' : 'duoxuan'" type="" @tap="post_answer_req">
						{{ is_duoxuan_sub ? "提交成功" : "确认答案" }}
					</button>
				</view>
				<question-pre-next v-if="timu_list.length > 0" :total_num="total_num" :timu_order="timu_order"
					:timu_list="timu_list" @choice_timu_by_id="choice_timu_by_id" @tap_handler="jiaojuan" confirmText="交卷"
					class="questionBankAnswer-contentbtnbox"></question-pre-next>
			</view>
			<view v-if="current_timu.type == 5" class="jdttishi">温馨提示：简答题不记入错题，默认为正确</view>
			<view style="height: 50px;"></view>
		</view>
		<view class="order-pay">
			<view class="questionBankAnswer-bottom-flex" @tap="jiaojuan1">
				<view class="iconfont icon-bianjisekuai"></view>
				<view>交卷</view>
			</view>
			<question-answer-sheet class="questionBankAnswer-bottom-flex"
				@show_choice_timu_list="show_choice_timu_list = true"></question-answer-sheet>
			<view class="questionBankAnswer-bottom-flex" @tap="show_change_moshi = true">
				<view class="iconfont icon-shezhi"></view>
				<view>设置</view>
			</view>
		</view>
		<question-answer-sheet-1 v-if="show_choice_timu_list" question_type="exam"
			@show_choice_timu_list="show_choice_timu_list = false" :timu_order="timu_order" :timu_list="timu_list"
			:total_num="total_num" @choice_timu_by_id="choice_timu_by_id" @jiaojuan1="jiaojuan1">
		</question-answer-sheet-1>
		<question-set :show_change_moshi="show_change_moshi" :if_theme_dark="if_theme_dark"
			@set_if_theme_dark="set_if_theme_dark" @hide_change_moshi="show_change_moshi = false"></question-set>
		<overtimu v-if="show_over_dati" :timuinfo="over_dati_info" @tap_handler="jiaojuan"></overtimu>
	</view>
</template>

<script>
import overtimu from "@/components/overtimu/index";
import {
	mapState
} from "vuex";

export default {
	data() {
		return {
			exam_id: 0, //考试id
			total_num: 0, //试题总数
			// 上次答到第几题
			timu_order: -1,
			//区分多选题是否点击提交按钮
			is_duoxuan_sub: false,
			is_tiankong_sub: false,
			is_jianda_sub: false,
			// 当前题目
			current_timu: {},
			// 用户输入的答案
			copy_user_answer: {},
			copy_right_answer_code: {},
			copy_post_status: {},
			// 是否显示退出答题弹框
			show_over_dati: false,
			over_dati_info: {},
			// 答题开始时间
			start_time: 0,
			end_time: 0,
			// 页面参数
			pages_params: {},
			// 显示答题卡
			show_choice_timu_list: false,
			// 答题卡
			timu_list: [],
			// 字号大小
			show_change_moshi: false,
			if_theme_dark: false // 黑夜模式
		};
	},
	onShow() { },
	onLoad(opts) {
		console.log('%c [ opts ]-121', 'font-size:13px; background:pink; color:#bf2c9f;', opts)
		this.pages_params = opts;
		this.exam_id = this.pages_params.id
		this.end_time = this.pages_params.end_time

		if (this.userinfo.token) {
			this.init()
		}
	},
	onReady() { },
	computed: {
		...mapState(["subject", "userinfo"]),
		over_time() {
			if (this.end_time > 0) {

				let end = parseInt(new Date().getTime() / 1000);
				let sec = parseInt(this.end_time - end);
				let hour = parseInt(sec / 3600);
				let miu = parseInt((sec - hour * 3600) / 60);
				let s = sec - hour * 3600 - miu * 60;
				console.log("endTime", hour);
				console.log("endTime", miu);
				console.log("endTime", s);
				return {
					hour: parseInt(hour),
					minute: parseInt(miu),
					second: parseInt(s)
				};
			}
			return {};
		}
	},
	onBackPress() {
		this.over_dati();
		return true;
	},
	components: {
		overtimu,
	},
	methods: {
		async init() {
			const info = await this.$myUserLogin.getExamVipInfo(this.exam_id);
			if (info.is_vip == 0 || info.owned_vip == 1) {
				this.get_timu_list();
			} else {
				//需要vip但还不是vip
				uni.showToast({
					title: '暂无权限',
					icon: 'none'
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 1500)
			}
		},
		set_sub_button_style(type, value) {
			console.log(type, value)
			this[type] = value
		},
		set_current_timu(data) {
			this.current_timu = JSON.parse(JSON.stringify(data))
			let copy_user_answer_this = this.copy_user_answer;
			if (copy_user_answer_this[this.current_timu.id]) {
				copy_user_answer_this[this.current_timu.id] = this.current_timu.my_answer_arr
			}
		},
		set_copy_user_answer(data) {
			this.copy_user_answer = JSON.parse(JSON.stringify(data))
			this.setAnswerStyle(this.current_timu);
			// this.setMyAnswer();
		},
		//单选多选判断，选项正确错误
		setAnswerStyle(timu) {
			this.$nextTick(() => {
				timu.answers.forEach((item, index) => {
					this.$refs['questionOption_' + index][0].setAnswerStyle(this.copy_user_answer);
				})
			})
		},
		timeup() {
			this.jiaojuan();
		},
		// 获取答题卡
		//2020年2月1日——创建一个答题卡数组   is_dati    1已答  0未答
		async get_timu_list() {
			let res = await this.$myHttp.post({
				url: this.$myHttp.urlMap.examCard,
				data: {
					exam_id: this.exam_id // 考试id
				},
				needLogin: true
			});

			if (res.code == 1) {
				this.timu_order = res.data.position
				this.timu_list = res.data.card;
				this.total_num = this.timu_list.length;
				this.isChangeTimu = false

				if (res.data.curr_question != []) {
					this.current_timu = res.data.curr_question;
					this.save_user_answer(this.current_timu);
				} else {
					this.current_timu = null
				}

				this.is_duoxuan_sub = false
				this.is_tiankong_sub = false
				this.is_jianda_sub = false
				// this.get_timu_order();
			}
		},
		// 获取用户答到第几题
		// async get_timu_order() {
		// 	let res = await this.$myHttp.post({
		// 		url: this.$myHttp.urlMap.examPosition,
		// 		data: {
		// 			exam_id: this.exam_id
		// 		},
		// 		needLogin: true
		// 	});

		// 	if (res.code == 1) {
		// 		this.timu_order = res.data
		// 		this.get_timu_info();
		// 	}
		// },
		async get_timu_info() {
			let res = await this.$myHttp.post({
				url: this.$myHttp.urlMap.exam_timu_details,
				data: {
					exam_id: this.exam_id,
					question_id: this.timu_list[this.timu_order - 1].id
				},
				needLogin: true
			});

			if (res.code == 1) {
				if (res.data != []) {
					this.isChangeTimu = false
					this.current_timu = res.data;
					this.save_user_answer(this.current_timu);
					this.is_duoxuan_sub = false
					this.is_tiankong_sub = false
					this.is_jianda_sub = false
				} else {
					this.current_timu = null;
				}
			} else {
				uni.navigateBack({});
			}
		},
		// 根据答题卡获取题目
		choice_timu_by_id(index) {
			this.timu_order = index + 1
			this.isChangeTimu = true
			// this.current_timu = {}
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 200
			});
			this.get_timu_info()
		},
		// 本地存储用户答案   考试页面
		save_user_answer(timu) {
			if (timu.type <= 3) {
				if (timu && timu.answers) {
					if (!(this.copy_user_answer[timu.id])) {
						this.copy_user_answer = Object.assign({}, this.copy_user_answer, {
							[timu.id]: []
						});
						this.copy_post_status = Object.assign({}, this.copy_post_status, {
							[timu.id]: false
						});
						for (let i = 0, leng = timu.answers.length; i < leng; i++) {
							this.copy_user_answer[timu.id].push({
								answer_code: timu.answers[i].answer_code,
								active: false
							})
						}
						if (timu.my_answer !== '' && timu.my_answer !== null) {
							this.setUserAnswer(timu)
						} else {
							this.setAnswerStyle(timu);
						}
					} else {
						this.setAnswerStyle(timu);
					}
				}
			} else {
				let right_answer_arr = timu.right_answer.split('|');
				this.$set(timu, 'right_answer_arr', right_answer_arr)
				this.$set(timu, 'show_right_answer', false)
				if (!(this.copy_user_answer[timu.id])) {
					//本地没有记录呢，如果my_answer有值，写进去
					this.copy_user_answer = Object.assign({}, this.copy_user_answer, {
						[timu.id]: []
					});
					this.copy_post_status = Object.assign({}, this.copy_post_status, {
						[timu.id]: false
					});
					if (timu.my_answer == '' || timu.my_answer == null) {
						//之前没有答过题
						let arr = [];
						arr.length = right_answer_arr.length;
						this.$set(timu, 'my_answer_arr', arr)
						this.$set(timu, 'my_answer', '')
						this.setAnswerStyle(timu);
					} else {
						//之前答过题了
						this.setUserAnswer(timu)
					}
				} else {
					//本地有答题记录  答过题了
					this.setUserAnswer(timu)
				}
			}
		},
		//获取题目信息后，如果答过题了，设置到本地
		setUserAnswer(timu) {
			this.copy_post_status = Object.assign({}, this.copy_post_status, {
				[timu.id]: true
			});
			let id = this.current_timu.id,
				answer = this.current_timu.my_answer;
			// 如果是判断和单选。执行以下处理
			if (timu.type == 1 || timu.type == 3) {
				for (let i = 0, leng = this.copy_user_answer[id].length; i < leng; i++) {
					if (this.copy_user_answer[id][i].answer_code.toString().toLowerCase().replace(/\s/g, "") ==
						answer.toString().toLowerCase().replace(/\s/g, "")) {
						this.copy_user_answer[id][i].active = true;
					} else {
						this.copy_user_answer[id][i].active = false;
					}
				}
			} else if (timu.type == 2) {
				// 如果是多选。执行以下处理
				for (let i = 0, leng = answer.length; i < leng; i++) {
					for (let j = 0, len = this.copy_user_answer[id].length; j < len; j++) {
						if (this.copy_user_answer[id][j].answer_code.toString().toLowerCase().replace(/\s/g, "") ==
							answer[i].toString().toLowerCase().replace(/\s/g, "")) {
							this.copy_user_answer[id][j].active = true;
						}
					}
				}
			} else {
				// 如果是填空，简答
				this.$set(timu, 'my_answer_arr', timu.my_answer.split('|'))
				this.$set(timu, 'my_answer', timu.my_answer)
				this.$set(timu, 'show_right_answer', true)
				this.copy_user_answer = Object.assign({}, this.copy_user_answer, {
					[timu.id]: []
				});
				this.copy_user_answer[timu.id].push(...timu.my_answer_arr)
			}
			this.setAnswerStyle(timu);
		},
		// 提交答案
		async post_answer_req() {
			this.is_duoxuan_sub = true;
			this.is_tiankong_sub = true
			this.is_jianda_sub = true

			let timu_index = this.timu_order - 1;
			let answer = "";
			if (this.current_timu.type <= 3) {
				let answers = this.copy_user_answer[this.current_timu.id];
				for (let i = 0, leng = answers.length; i < leng; i++) {
					if (answers[i].active) {
						answer += answers[i].answer_code;
					}
				}
				this.copy_post_status = Object.assign({}, this.copy_post_status, {
					[this.current_timu.id]: true
				});
			}

			let res = await this.$myHttp.post({
				url: this.$myHttp.urlMap.exam_answer,
				data: {
					question_id: this.current_timu.id,
					exam_id: this.exam_id,
					answer: this.current_timu.type <= 3 ? answer : this.current_timu.my_answer
				},
				needLogin: true
			});
			if (res.code == 1 && res.msg) {
				this.timu_list[timu_index].state = 1;
			}
		},
		jiaojuan1() {
			uni.showModal({
				title: '提示',
				content: '是否立即交卷',
				showCancel: true,
				cancelText: '继续答题',
				confirmText: '立即交卷',
				success: res => {
					if (res.confirm) {
						this.jiaojuan();
					}
				},
				fail: () => { },
				complete: () => { }
			});
		},
		async jiaojuan() {
			if (this.exam_id) {
				let res = await this.$myHttp.post({
					url: this.$myHttp.urlMap.exam_end,
					data: {
						exam_id: this.exam_id
					},
					needLogin: true
				});
				if (res.code == 1) {
					this.$myCatch.setItem("jiaojuan_info", res.msg);
					this.tap_handler();
				} else {
					uni.navigateBack({
						delta: 1
					});
				}
			} else {
				uni.navigateBack({
					delta: 1
				});
			}
		},
		// 中途退出
		over_dati() {
			let that = this;
			that.$myUtils.$prompt.showModal({
				title: "提示",
				content: "是否交卷",
				confirmText: "交卷",
				success: function (res) {
					if (res.confirm) {
						that.jiaojuan();
					} else if (res.cancel) {
						console.log("用户点击取消");
					}
				}
			});
		},
		// 设置是否黑夜模式
		set_if_theme_dark(data) {
			this.if_theme_dark = data
		},
		tap_handler(type) {
			if (type == 0) {
				this.show_over_dati = false;
			} else {
				this.$redirectTo("/pages/examination/examOver/index");
			}
		},
	}
};
</script>

<style>
@import "~@/static/css/tiku.css";

.questionBankAnswer-content-menu .active {
	background: #3c7bfc !important;
}
</style>
